// 1. 导包
import { createRouter, createWebHashHistory } from 'vue-router'
import LoginView from '@/view/LoginView.vue'
import request from '@/utils/request'  // 你封装的 axios 请求工具

// 2. 路由表
const routes = [
    {
        name: 'index',
        path: '/',
        component: LoginView
    },
    {
        name: 'login',
        path: '/login',
        component: () => import('@/view/LoginView.vue')
    },
    {
        name: 'main',
        path: '/main',
        component: () => import('@/view/MainView.vue'),
        // children 后面动态添加
        children: []
    }
]

// 3. 创建路由器
const router = createRouter({
    history: createWebHashHistory(),
    routes
})

// 4. 登录拦截守卫
let dynamicRoutesAdded = false  // 防止多次添加
router.beforeEach(async (to, from, next) => {
    const user = sessionStorage.getItem("user")

    if (!user && to.path !== '/' && to.path !== '/login') {
        next('/')
    } else {
        // 添加动态菜单路由（只添加一次）
        if (!dynamicRoutesAdded && user) {
            await getUserMenuAndAddRoutes()
            dynamicRoutesAdded = true
            next({ ...to, replace: true })  // 重新跳转，确保新路由生效
            return
        }
        next()
    }
})

// 5. 获取用户菜单权限并动态添加子路由
async function getUserMenuAndAddRoutes() {
    try {
        const res = await request.get('/user/router') 
        const menuList = res.data.list 
        // console.log(menuList);
        

        // 遍历菜单并添加为子路由
        menuList.forEach(menu => {
            // console.log(menu);
            const route = {
                path: menu.path,  // '/user'
                name: menu.name,  // 'user'
                component: () => import(`@/view/${menu.component}.vue`)  // UserView.vue
            }
            router.addRoute('main', route)  // 添加到main的children中
        })
        // console.log(router.addRoute);
        

    } catch (err) {
        console.error('获取菜单失败', err)
    }
}

// 6. 导出
export default router
